import axios from "axios";
import type {
    AxiosInstance,
    AxiosError,
    InternalAxiosRequestConfig,
    AxiosResponse,
    AxiosRequestConfig,
} from "axios";
import { ElMessage } from "element-plus";

const URL: string = "";

enum RequestEnums {
    TIMEOUT = 20000,
    OVERDUE = 600, //登录失败
    FAIL = 999, //请求失败
    SUCCESS = 200, //登录成功的code
}

const instance: AxiosInstance = axios.create({
    baseURL: '/',
    timeout: 500000,
});
// instance.interceptors.request.use(
//     (config: InternalAxiosRequestConfig) => {
//         const token = localStorage.getItem("token");
//         if (token) {
//             config.headers.Authorization = "Bearer " + token;
//         }
//         return config;
//     },
//     (error: AxiosError) => {
//         return Promise.reject(error);
//     }
// );

instance.interceptors.response.use(
    (response: AxiosResponse) => {
        return response;
    },
    (error: AxiosError) => {
        let message = "";
        let code = error.response?.status;
        if (code) {
            switch (code) {
                case 401:
                    message = "token过期";
                    break;
                case 403:
                    message = "无权访问";
                    break;
                case 404:
                    message = "请求地址错误";
                    break;
                case 500:
                    message = "服务器出现问题";
                    break;
                default:
                    message = "其他错误";
            }
        }
        ElMessage.error(message);
        return Promise.reject(error);
    }
);

const service = {
    get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
        return instance.get(url, config);
    },

    post<T = any>(
        url: string,
        data?: object,
        config?: AxiosRequestConfig
    ): Promise<T> {
        return instance.post(url, data, config);
    },
};

export default service;
